from flask import request
from flask_shop.role import role_bp,role_api
from flask_restful import Resource,reqparse
from flask_shop.models import Role,Menus
from flask_shop import db


class Roles(Resource):
    def get(self):
        role_list = Role.query.all()
        data = [r.to_dict() for r in role_list]
        return {'status':200,'msg':'获取成功','data':data}
            
    def post(self):
        try:
            #新增数据
            name = request.get_json().get('name')
            desc = request.get_json().get('desc')
            if not all([name,desc]):
                return {'status':400,'msg':'参数不完整'}
            else:
                role = Role(name = name,desc = desc)
                db.session.add(role)
                db.session.commit()
                return {'status':200,'msg':'添加成功'}
        except Exception as e:
            if 'Duplicate entry' in str(e):
                return {'status':400,'msg':'角色已存在'}
            else:
                return {'status':400,'msg':'添加异常'}
            
class Role_handle(Resource):
    def get(self,id):
        role =Role.query.get(id)
        return {'status':200,'msg':'获取成功','data':role.to_dict()}


    def put(self,id):
        try:
            role_id = Role.query.get(id)
            parser = reqparse.RequestParser()
            parser.add_argument('name',type=str)
            parser.add_argument('desc',type=str)
            args = parser.parse_args()
            name = args.get('name')
            desc = args.get('desc')   
            role_id.name = name
            role_id.desc = desc
            db.session.commit()

            return {'status':200,'msg':'修改成功'}
        except Exception as e:

            if 'Duplicate entry' in str(e):
                return {'status':400,'msg':'角色已存在'}
            return {'status':400,'msg':'修改失败'}


    def delete(self,id):
        try:
            role = Role.query.get(id)
            db.session.delete(role)
            db.session.commit()
            return {'status':200,'msg':'删除成功'}
        except Exception as e:
            return {'status':400,'msg':'删除失败'}

@role_bp.route('/role/<int:rid>/<int:mid>/')
def del_role_menu(rid,mid):
    #查找角色信息
    role = Role.query.get(rid)
    #查找菜单信息
    menu = Menus.query.get(mid)
    if all([role,menu]):
        if menu in role.menus:
            role.menus.remove(menu)
            if menu.level == 1 and menu.children:
                for c in menu.children:
                    if c in role.menus:
                        role.menus.remove(c)
        db.session.commit()
        return {'status':200,'msg':'删除角色菜单成功'}
    else:
        return {'status':400,'msg':'删除失败'}

role_api.add_resource(Roles,'/role/')
role_api.add_resource(Role_handle,'/role_handle/<int:id>/')

@role_bp.route('/role/<int:rid>/',methods=['POST'])
def set_menu(rid):
    try:
        #查询角色信息
        role = Role.query.get(rid)  
        #获取菜单列表字符串
        mids = request.get_json().get('mids').split(',')
        #将role的menu置空
        role.menus = []
        for m in mids:
            if m:
                menu = Menus.query.get(int(m))
                role.menus.append(menu)
        db.session.commit()
        return {'status':200,'msg':'分配成功'}
    except Exception as e:
        return {'status':400,'msg':'分配失败'}
